#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <time.h>

//一个内存页的大小
#define PIGE_SIZE 4*1024

int main(int argc, const char *argv[])
{
    key_t my_key = 0;
    int shmid = 0;
    char *p_addr = NULL;
    //获取键值
    if(-1 == (my_key = ftok("/home", 'H'))){
        perror("ftok error");
        exit(-1);
    }

    //创建共享内存
    if(-1 == (shmid = shmget(my_key, PIGE_SIZE, IPC_CREAT|0664))){
        perror("shmget error");
        exit(-1);
    }

    //映射共享内存
    if((void *)-1 == (p_addr = shmat(shmid, NULL, 0))){
        perror("shmat error");
        exit(-1);
    }

    //向共享内存写数据
    fgets(p_addr, 1024, stdin);
    p_addr[strlen(p_addr) - 1] = '\0';

    //获取共享内存属性
    struct shmid_ds shd;
    shmctl(shmid,IPC_STAT,&shd);
    printf("size = %ld\n",shd.shm_segsz);
    printf("attach=%ld\n",shd.shm_nattch);
    printf("create pid = %d,pid = %d\n",shd.shm_cpid,getpid());
    printf("last pid = %d\n",shd.shm_lpid);
    printf("tim = %ld\n",shd.shm_ctime);
    struct tm *tm;
    tm = localtime(&shd.shm_ctime);
    printf("%d-%02d-%02d %02d:%02d:%02d\n",
            tm->tm_year+1900,tm->tm_mon+1,tm->tm_mday,tm->tm_hour,tm->tm_min,tm->tm_sec);

    //取消映射
    if(-1 == shmdt(p_addr)){
        perror("shmdt error");
        exit(-1);
    }

    //删除共享内存
    shmctl(shmid, IPC_RMID, NULL);

    return 0;
}